with Stations; use Stations;
with Constants; use Constants;
with Folk; use Folk;
with Ada.Text_IO; use Ada.Text_IO;

package body Trains is
   task body Train is

      nextStation: StationType;
      queue: Passengers_Container.Vector;
      queueNew: Passengers_Container.Vector;
      St: Boolean;

      function getNextStation(lastStation: StationType) return StationType is
      begin
         if (lastStation = StationType'Last) then
            return StationType'First;
         else
            return StationType'Succ(lastStation);
         end if;
      end getNextStation;

   begin

      -- Zadajom pervuju stanciju na kotoruju pribudet poezd - Station "A"
      nextStation := StationType'First;

      -- Cikli4noe dvizenie poezda
      for i in 1..NumberOfStationsToVisit loop

         -- Vremja kotoroe poezd tratit v dvizenije

         delay duration(TrainWayTime);

	-- Govorim 4to poezd pribl na stanciju
         StationsList(nextStation).comeTrain;

         -- volshebnaja proverka
        if not queue.Is_Empty then
	queueNew.Clear;
         -- Vsem posaziram kotorie v poezde govorim 4to oni mogut vijti
            for i in queue.First_Index..queue.Last_Index loop
            Passengers(queue.Element(Index => i)).LeaveTrain(St, nextStation);

            -- Proverjaem vishel li posazir, esli da udaljaem ego iz poezda

               if not St then
                  queueNew.Append(New_Item => queue.Element(Index => i));

               end if;

            end loop;
	queue:=queueNew;
        end if;



         -- Vremja kotoroe poezd stoit na stancii
         delay duration(TrainWaitingTime);
         queueNew.Clear;
         -- Govotim stancii 4to poezd uezzaet i polu4aem spisok posazirov
         StationsList(nextStation).leaveTrain(queueNew);

         -- Polu4enim posaziram govorim 4to ini mogut zajti v poezd
        if not queueNew.Is_Empty then

            for i in queueNew.First_Index..queueNew.Last_Index loop
               Passengers(queueNew.Element(Index => i)).MoveToTrain;
            end loop;
        end if;

         queue.Append(New_Item => queueNew);

         -- Opredeljaem sledujus4uju stanciju kotoruju poezd dolzen posetitj
         nextStation := getNextStation(nextStation);

      end loop;

   end Train;
end Trains;


